package cn.doitedu.rtmk.demo5;

import cn.doitedu.rtmk.beans.UserEvent;
import cn.doitedu.rtmk.interfaces.IRuleCalculatorV1;
import cn.doitedu.rtmk.interfaces.IRuleCalculatorV2;
import cn.doitedu.rtmk.interfaces.IRuleCalculatorV3;
import cn.doitedu.rtmk.utils.RuleHitResultBuilder;
import com.alibaba.fastjson.JSONObject;
import org.apache.flink.api.common.functions.RuntimeContext;
import org.apache.flink.util.Collector;
import org.roaringbitmap.RoaringBitmap;

/**
 * @Author: deep as the sea
 * @Site: <a href="www.51doit.com">多易教育</a>
 * @QQ: 657270652
 * @Date: 2023/4/14
 * @Desc: 学大数据，到多易教育
 *  规则模型1的运算机逻辑类
 **/
public class RuleModel1Calculator implements IRuleCalculatorV2 {
    RoaringBitmap preSelectUsersBitmap;
    // {"rule_id":1,"rule_model_id":1,"triggerEventId":"page_load","triggerEventPropertyName":"url","triggerEventPropertyValue":"/page/001"}
    JSONObject ruleInstanceParams;

    @Override
    public void open(RoaringBitmap preSelectUsersBitmap, JSONObject ruleInstanceParams) {
        this.preSelectUsersBitmap = preSelectUsersBitmap;
        this.ruleInstanceParams = ruleInstanceParams;


    }

    @Override
    public void calc(UserEvent userEvent, Collector<JSONObject> out) {
        // 先判断该用户是否是本规则的目标人群
        if (preSelectUsersBitmap.contains((int) userEvent.getUser_id())) {
            // 判断该行为是否是本规则的触发条件

            // 从参数中获取本规则所要求的触发事件ID
            String triggerEventId = ruleInstanceParams.getString("triggerEventId");
            // 从参数中获取本规则所要求的触发事件的属性条件： 属性名和属性值
            String triggerEventPropertyName = ruleInstanceParams.getString("triggerEventPropertyName");
            String triggerEventPropertyValue = ruleInstanceParams.getString("triggerEventPropertyValue");

            if (userEvent.getEvent_id().equals(triggerEventId) && userEvent.getProperties().get(triggerEventPropertyName).equals(triggerEventPropertyValue)) {
                // 如果是，则推送消息
                JSONObject resultObj = new RuleHitResultBuilder()
                        .setUser(userEvent.getUser_id())
                        .setHitTime(userEvent.getEvent_time())
                        .setHitRule(ruleInstanceParams.getInteger("rule_id"))
                        .setHitRuleModel(ruleInstanceParams.getInteger("rule_model_id"))

                        .build();

                out.collect(resultObj);
            }
        }
    }
}
